<template>
	<view class="cu-modal bottom-modal" :class="{ show: showAuth }" @tap="closeAuthModal" style="z-index: 10080;">
    <view class="page-container cu-dialog safe-area-inset-bottom" @tap.stop>
      <!-- 1.账号密码登录 -->
      <AccountLogin
        :protocol="protocol"
        :placeholderStyle="placeholderStyle"
        :checkValue="checkValue"
        :validation="validation"
        :validateAll="validateAll"
        :validateSubmit="validateSubmit"
        :closeAuthModal="closeAuthModal"
      />
    
      <!-- 2.短信登录 -->
      <SmsLogin
        v-if="authType === 'smsLogin'"
        :protocol="protocol"
        :placeholderStyle="placeholderStyle"
        :checkValue="checkValue"
        :validation="validation"
        :validateAll="validateAll"
        :validateSubmit="validateSubmit"
        :closeAuthModal="closeAuthModal"
        :codeText="codeText"
        :mobileInput="mobileInput"
        :getSmsCode="getSmsCode"
      />
      
      <!-- 3.注册 -->
      <Register
        v-if="authType === 'register'"
        :protocol="protocol"
        :placeholderStyle="placeholderStyle"
        :checkValue="checkValue"
        :validation="validation"
        :validateAll="validateAll"
        :validateSubmit="validateSubmit"
        :closeAuthModal="closeAuthModal"
        :mobileInput="mobileInput"
        :getSmsCode="getSmsCode"
      />
    
      <!-- 4.忘记密码 -->
      <ForgotPassword
        v-if="authType === 'forgotPwd'"
        :protocol="protocol"
        :placeholderStyle="placeholderStyle"
        :checkValue="checkValue"
        :validation="validation"
        :validateAll="validateAll"
        :validateSubmit="validateSubmit"
        :closeAuthModal="closeAuthModal"
        :codeText="codeText"
      />
    
      <!-- 5.绑定手机号 -->
      <BindMobile
        v-if="authType === 'bindMobile'"
        :protocol="protocol"
        :placeholderStyle="placeholderStyle"
        :checkValue="checkValue"
        :validation="validation"
        :validateAll="validateAll"
        :validateSubmit="validateSubmit"
        :closeAuthModal="closeAuthModal"
      />
    
      <!-- 6.修改密码 -->
      <ChangePassword
        v-if="authType === 'changePwd'"
        :protocol="protocol"
        :placeholderStyle="placeholderStyle"
        :checkValue="checkValue"
        :validation="validation"
        :validateAll="validateAll"
        :validateSubmit="validateSubmit"
        :closeAuthModal="closeAuthModal"
      />
    
      <!-- 第三方登录 -->
      <view v-if="authType === 'accountLogin' || authType === 'smsLogin'" class="auto-login-box u-flex u-row-center u-col-center">
        <!-- 微信 -->
        <!-- <image
          v-if="['App', 'wxOfficialAccount', 'wxMiniProgram'].includes(platform)"
          class="auto-login-img"
          @tap="thirdLogin('wechat')"
          :src="$IMG_URL + '/imgs/auto_login_wx.png'"
          mode=""
        ></image> -->
        <!-- 支付宝 -->
        <!-- <image
          v-if="['App', 'alipayMiniProgram', 'H5'].includes(platform)"
          class="auto-login-img"
          @tap="thirdLogin('alipay')"
          :src="$IMG_URL + '/imgs/auto_login_ali.png'"
          mode=""
        ></image> -->
        <!-- 苹果 -->
        <!-- #ifdef APP-PLUS -->
        <!-- <image v-if="device === 'ios'" class="auto-login-img" @tap="thirdLogin('apple')" :src="$IMG_URL + '/imgs/auto_login_iphone.png'" mode=""></image> -->
        <!-- #endif -->
      </view>
    
      <!-- 协议 -->
      <view v-if="['accountLogin', 'smsLogin', 'register'].includes(authType)" class="agreement-box u-flex u-row-center">
          <u-checkbox v-model="protocol" shape="circle">
            <view class="agreement-text tcp-text u-flex u-col-center">
              我已阅读并遵守
              <view class="tcp-text u-flex u-col-center">
                <view @tap.stop="$Router.push({ path: '/pages/public/richtext', query: { id: initStore.shop.user_protocol || 0 } })">《用户协议》</view>
                与
                <view @tap.stop="$Router.push({ path: '/pages/public/richtext', query: { id: initStore.shop.privacy_protocol || 0 } })">《隐私协议》</view>
              </view>
            </view>
          </u-checkbox>
        </view>
    
      <ChoiseIdentify v-if="authType === 'choiseIdentify'" />
      
      <BindSelf v-if="authType === 'bindSelf'" />
      
      <BindChildren v-if="authType === 'bindChildren'" />
      
      <AddChild v-if="authType === 'addChild'" />
    </view>
   </view>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';
import FormValidate from '@/utils/validate/form';
import schema from '@/uview-ui/libs/util/async-validator';
import wechat from '@/utils/wechat/wechat';

import AccountLogin from './account-login';
import SmsLogin from './sms-login';
import Register from './register';
import ForgotPassword from './forgot-password';
import BindMobile from './bind-mobile';
import ChangePassword from './change-password';
import ChoiseIdentify from './choise-identity';
import BindSelf from './bind-self';
import BindChildren from './bind-children';
import AddChild from './add-child';

// #ifdef APP-PLUS
import apple from '@/utils/apple';
// #endif

export default {
	name: 'rhinoAuthModal',
  components: {
    AccountLogin,
    SmsLogin,
    Register,
    ForgotPassword,
    BindMobile,
    ChangePassword,
    ChoiseIdentify,
    BindSelf,
    BindChildren,
    AddChild,
  },
	data() {
		return {
			platform: this.$platform.get(),
			device: this.$platform.device(),
			codeText: '获取验证码',
			disabledCode: false,
			protocol: false, //是否同意隐私协议
			placeholderStyle: 'font-size: 30rpx; font-weight: 500;color:#C2C7CF;'
		};
	},

	computed: {
		...mapGetters(['initStore', 'isLogin','authType']),
		showAuth: {
			get() {
				return !!this.authType;
			},
			set(value) {
				value ? uni.hideTabBar() : uni.showTabBar();
			}
		}
	},
	methods: {
		...mapActions(['getUserInfo', 'showAuthModal']),

		// 检测
		checkValue(e, key) {
			this.validation(key);
		},

		// 校验数据
		validation(key, callback = () => {}) {
			let that = this;
			//拿到需要校验的数据
			let fieldValue = this.form.data[key];
			//拿到需要检验的规则
			let rules = this.form.rules[key];
			// 判空
			if (!rules || rules.length === 0) {
				return callback('');
			}
			// 设置当前的装填，标识为校验中
			let validateState = 'validating';
			// 调用async-validator的方法
			let validator = new schema({
				[key]: rules
			});
			// 校验
			validator.validate(
				{
					[key]: fieldValue
				},
				{
					firstFields: true
				},
				(errors, fields) => {
					// 记录状态和报错信息
					validateState = !errors ? 'success' : 'error';
					let validateMessage = errors ? errors[0].message : '';
					that.form.error[key] = validateMessage;
					callback(validateMessage);
				}
			);
		},

		// 校验全部数据
		validateAll(callback) {
			let that = this;
			return new Promise(resolve => {
				// 对当前所有表单检验
				let valid = true; // 默认通过
				let count = 0; // 用于标记是否检查完毕
				let errorArr = []; // 存放错误信息
        
				let curFormData = that.form.data;

				Object.keys(curFormData).map(field => {
					that.validation(field, error => {
						// 如果回调有error
						if (error) {
							valid = false;
							errorArr.push(error);
						}
						if (++count === Object.keys(curFormData).length) {
							resolve(valid);
							if (errorArr.length) {
								this.$u.toast(errorArr[0]);
							}
							if (typeof callback == 'function') callback(valid);
						}
					});
				});
			});
		},

		// 手机号是否输入完毕
		mobileInput(e, key) {
			this.form.data.isMobileEnd = this.$u.test.mobile(this.form.data.mobile);
			this.validation(key);
		},

		closeAuthModal() {
			this.$store.dispatch('showAuthModal', '');
		},

		// 获取短信验证码
		getSmsCode(type) {
			const that = this;
			if (that.form.data.isMobileEnd && !that.disabledCode) {
				that.$http(
					'common.smsSend',
					{
						mobile: that.form.data.mobile,
						event: type
					},
					'获取验证码中...'
				).then(res => {
					if (res.code === 1) {
						that.codeChange();
						that.$u.toast('验证码已发送，请注意查收短信');
					} else {
						that.$u.toast(res.msg);
					}
				});
			} else {
				that.$u.toast('请稍后再试');
			}
		},

		// 倒计时
		codeChange() {
			if (this.disabledCode) return;
			this.disabledCode = true;
			let n = 10;
			this.codeText = n + 's';
			const run = setInterval(() => {
				n -= 1;
				if (n < 0) {
					clearInterval(run);
				}
				this.codeText = n + 's';
				if (this.codeText < 0 + 's') {
					this.disabledCode = false;
					this.codeText = '重新获取';
				}
			}, 1000);
		},

		// 规则校验
		validateSubmit() {
			if (['accountLogin', 'smsLogin', 'register'].includes(this.authType) && !this.protocol) {
				this.$u.toast('请同意用户协议');
				return false;
			}
      
			return this.validateAll();
		},

		// 第三方登录
		async thirdLogin(provider) {
			if (!this.protocol) {
				this.$u.toast('请同意用户协议');
				return false;
			}
			const that = this;
			let token = '';
			switch (provider) {
				case 'wechat':
					token = await wechat.login();
					break;
				case 'alipay':
					break;
				case 'apple':
					token = await apple.appleIdOauth();
					break;
				default:
					break;
			}
			if (token) {
				that.closeAuthModal();
				that.getUserInfo(token);
			}
		},
	}
};
</script>

<style lang="scss" scoped>
@import './style.scss';

.page-container {
  height: 100%;
  background-color: #fff;
}
</style>
